<template>
  <div>
    <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.teamName" placeholder="代表队名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.realName" placeholder="选手姓名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.company" placeholder="单位" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.status" placeholder="状态">
          <el-option value="">全部</el-option>
          <el-option label="审核中" value="0"></el-option>
          <el-option label="报名成功" value="1"></el-option>
          <el-option label="完赛" value="2"></el-option>
          <el-option label="已取消/弃权" value="3"></el-option>
          <el-option label="比赛中" value="4"></el-option>
          <el-option label="已获晋级赛资格" value="5"></el-option>
          <el-option label="晋级成功" value="6"></el-option>
          <el-option label="弃权" value="7"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">{{ $t("query") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPermission('sp:spmatchitemrecord:genNo')" type="primary" @click="createCertificateNo()">生成证书编号</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="hasPermission('sp:spmatchitemrecord:genPic')" @click="certificateHandle()">生成证书图片</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportSignRecordTeacher()">导出(全组别)</el-button>
      </el-form-item>
      <el-form-item>
        <el-tag size="big">{{ matchItem ? matchItem.match_name : "" }}</el-tag>
        <el-tag size="big" style="margin-left: 10px">{{ matchItem ? matchItem.item_name : "" }}</el-tag>
        <el-tag size="big" style="margin-left: 10px">{{ dataForm.groupNameFile ? dataForm.groupNameFile : "" }}</el-tag>
      </el-form-item>
    </el-form>
    <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="teamName" label="代表队名称" header-align="center" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="teamHandle(scope.row.teamId)">{{ scope.row.teamName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="realName" width="250" label="指导老师" header-align="center" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="detailHandle(scope.row.userId)">{{ scope.row.realName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="company" label="学校/单位" header-align="center" align="center"></el-table-column>
      <el-table-column prop="certificate" width="250" label="证书编号" header-align="center" align="center"></el-table-column>
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150" v-if="hasPermission('sp:spmatchitemrecord:opra')">
        <template v-slot="scope">
          <el-button type="text" size="small" v-if="scope.row.certificate && hasPermission('sp:spmatchitemrecord:uploadCer')" @click="showUploadHandle(scope.row.id)">上传证书</el-button>
          <el-button type="text" size="small" v-if="scope.row.certificate_url && hasPermission('sp:spmatchitemrecord:infoCer')" @click="infoHandle(scope.row.certificate_url)">证书</el-button>
          <el-button type="text" size="small" v-if="scope.row.certificate_url && hasPermission('sp:spmatchitemrecord:downCer')" @click="downloadHandle(scope.row.certificate_url, scope.row.realName + '-' + scope.row.certificate)">下载</el-button>
          <el-button type="text" size="small" v-if="scope.row.certificate && hasPermission('sp:spmatchitemrecord:delCerNo')" @click="updateHandle(scope.row.id)">删除编号+图片</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle" @current-change="pageCurrentChangeHandle"> </el-pagination>
    <!-- 字典类型数据 -->
    <el-drawer :title="focusDictTypeTitle" v-model="dictTypeListVisible" :size="800" close-on-press-escape="false" custom-class="rr-drawer">
      <DictTypeList :dictTypeId="focusDictTypeId"></DictTypeList>
    </el-drawer>
    <TeamDetail v-if="teamVisible" ref="teamRef" @refreshDataList="getDataList"></TeamDetail>
    <detail v-if="detailVisible" ref="send" @refreshDataList="getDataList"></detail>
    <!--上传证书弹窗-->
    <el-dialog v-model="uploadVisible4" title="上传证书" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-upload class="text-center" drag :action="picUploadUrl" :show-file-list="false" :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, 'pic4')">
        <img v-if="dataForm.zsPic" :src="dataForm.zsPic" class="avatar" width="100" height="150" />
        <el-icon v-if="!dataForm.zsPic" class="el-icon--upload"><upload-filled /></el-icon>
        <div v-if="!dataForm.zsPic" class="el-upload__text" v-html="$t('upload.text')"></div>
      </el-upload>
      <div style="text-align: center; margin-top: 20px">
        <el-button @click="uploadVisible4 = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpload">确定上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import useView from "@/hooks/useView";
import { defineComponent, reactive, toRefs } from "vue";
import baseService from "@/service/baseService";
import DictTypeList from "@/views/sp/spteamuser.vue";
import TeamDetail from "@/views/sp/spteam-detail.vue";
import app from "@/constants/app";
import qs from "qs";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import Detail from "@/views/sp/spuser-detail.vue";
export default defineComponent({
  name: "RenRecordTeacher",
  components: {
    DictTypeList,
    TeamDetail,
    Detail
  },
  setup() {
    const state = reactive({
      uploadVisible4: false,
      picUploadUrl: "",
      getDataListURL: "/sp/spmatchitemteam/signRecordTeacher",
      createdIsNeed: false,
      activatedIsNeed: false,
      getDataListIsPage: true,
      exportURL: "/sp/spmatchitemteam/export",
      deleteURL: "/sp/spmatchitemteam",
      deleteIsBatch: true,
      dataForm: {
        matchName: "",
        item: "",
        matchItemId: "",
        matchItemName: "",
        teamId: "",
        teamName: "",
        isRise: "",
        status: "",
        company: "",
        realName: "",
        groupId: "",
        groupNameFile: "",
        zsPic: "",
        matchItemTeamUserId: ""
      },
      matchItem: {
        match_name: "",
        item_name: ""
      },
      activeName: "first",
      dictTypeListVisible: false,
      focusDictTypeId: "",
      focusDictTypeTitle: "",
      detailVisible: false,
      teamVisible: false,
    });
    return { ...useView(state), ...toRefs(state) };
  },
  watch: {},
  mounted() {
    this.picUploadUrl = `${app.api}/sys/oss/upload?token=${getToken()}`;
    //获取上个页面传来的参数
    this.dataForm.matchItemId = this.$route.query.matchItemId + "";
    this.dataForm.groupId = this.$route.query.id + "";
    this.dataForm.groupNameFile = this.$route.query.groupName + "";
    this.queryBymatchItemId(this.dataForm.matchItemId);
    this.query();
  },
  methods: {
    detailHandle(id?: string) {
      this.detailVisible = true;
      baseService.get("/sp/spuser/" + id).then((e: any) => {
        this.$nextTick(() => {
          if (e.data) {
            e.data.sex = e.data.sex == 0 ? "女" : "男";
          }
          this.$refs.send.dataForm.row = e.data;
          this.$refs.send.init();
        });
      });
    },
    //查询赛项详情
    queryBaseMatchItem() {
      baseService.post("/sp/spmatchitem/queryBaseMatchItem", { id: this.dataForm.matchItemId }).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        } else {
          let data = res.data;
        }
      });
    },
    zhengshuHandle() {
      let ids: string[] = [];
      for (let i = 0; i < this.dataListSelections!.length; i++) {
        ids.push(this.dataListSelections![i].id);
      }
      window.location.href = `${app.api}/sp/spmatchitemteam/downloadFile?${qs.stringify({
        ...this.dataForm,
        token: getToken(),
        ids: ids.join(",")
      })}`;
    },

    updateHandle(id: number) {
      this.$confirm("确认删除编号+图片？", "删除编号+图片", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/delCertificate?id=" + id, {}).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },

    /**
     * 查询score配置
     * @param matchItemId
     */
    queryBymatchItemId(matchItemId: any) {
      baseService.post("/sp/spmatchitem/queryBymatchItemId", { id: matchItemId }).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        } else {
          console.log(res.data);
          this.matchItem = res.data;
        }
      });
    },

    /**
     * 生成证书编号
     */
    createCertificateNo() {
      this.$confirm("确认生成证书编号？", "生成证书编号", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/createCertificateNoTeacher", this.dataForm).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    /**
     * 生成证书图片
     * @param id
     */
    certificateHandle(id?: string) {
      this.$confirm("确认生成证书？", "生成证书", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/certificateTeacher", this.dataForm).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    // 查看证书
    infoHandle(info: string) {
      window.open(info);
    },
    downloadHandle(url: string, name: string) {
      let a = document.createElement("a");
      let evt = document.createEvent("MouseEvents");
      a.download = "晋级列表";
      a.href = `${app.api}/sp/spticket/download?imageUrl=` + url + `&fileName=` + name;
      evt.initEvent("click", true, true);
      a.dispatchEvent(evt);
      window.URL.revokeObjectURL(a.href);
    },

    showTypeList(row: IObject) {
      this.dictTypeListVisible = true;
      this.focusDictTypeId = row.id;
      this.focusDictTypeTitle = `领队成员列表`;
    },

    // 上传证书弹窗
    showUploadHandle(id: any) {
      this.uploadVisible4 = true;
      this.dataForm.zsPic = "";
      this.dataForm.matchItemTeamUserId = id;
    },
    // 上传证书后保存
    handleAvatarSuccess(res: IObject, file: IObject, fileList: IObject, type: string) {
      this.dataForm.zsPic = res.data.src;
      this.$message.success("上传成功");
    },
    // 确定上传
    confirmUpload() {
      baseService.post("/sp/spmatchitemteamuser/updCertificate", { id: this.dataForm.matchItemTeamUserId, certificateUrl: this.dataForm.zsPic, type: "teacher" }).then((e: any) => {
        this.uploadVisible4 = false;
        this.query();
      });
    },
    // 导出指导老师
    exportSignRecordTeacher() {
      this.dataForm.matchName = this.matchItem.match_name;
      this.dataForm.matchItemName = this.matchItem.item_name;
      window.location.href = `${app.api}/sp/spmatchitemteam/exportSignRecordTeacher?${qs.stringify({
        ...this.dataForm,
        token: getToken()
      })}`;
    },
    teamHandle(id?: string) {
      this.teamVisible = true;
      baseService.get("/sp/spteam/" + id).then((e: any) => {
        this.$nextTick(() => {
          if (e.data) {
            e.data.sex = e.data.sex == 0 ? "女" : "男";
          }
          this.$refs.teamRef.dataForm.row = e.data;
          this.$refs.teamRef.init();
        });
      });
    },

  }
});
</script>
